<template>
  <div class="layout-container">
    <split-pane split="vertical" :min-percent="15" :default-percent="15" :max-percent="50">
      <template slot="paneL">
        <div class="left-container">
          <el-tree
            ref="tree"
            style="margin-top: 20px"
            class="filter-tree"
            :data="orgOption"
            :props="defaultProps"
            node-key="id"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <!--可以根据情况，以数据类型来显示不同的图标或图片-->
              <i v-if="(data.children && data.children.length) || data.parentId === '0'" :class="node.expanded ?'co-icon-zg-folder-opened-fill' : 'co-icon-folder_opened'" />
              <i v-else class="el-icon-document" />
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
      </template>
      <template slot="paneR">
        <div class="right-container">
          <basic-page-vxe
            ref="basePage"
            list-api="findSysAreaByCondition"
            del-api="deleteSysAreaById"
            :search-form="basicData.searchForm"
            :search-handle="basicData.searchHandle"
            :columns="basicData.columns"
            :is-auto="false"
            :search-other-data="basicData.searchOtherData"
            :is-tree-data="true"
            :show-pagination="false"
          />
        </div>
      </template>
    </split-pane>
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="510px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="170px" style="width: 100%">
        <el-form-item label="生产单位" prop="areaOrgId">
          <el-select v-model="temp.areaOrgId" filterable placeholder="请选择" style="width: 300px;" value-key="id">
            <el-option
              v-for="(item) in orgOption"
              :key="item.id"
              :label="item.prodOrgName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区块名称" prop="areaName">
          <el-input v-model="temp.areaName" placeholder="请输入" minlength="3" maxlength="64" clearable />
        </el-form-item>
        <el-form-item label="区块代码（对接A2）" prop="areaCode">
          <el-input v-model="temp.areaCode" placeholder="请输入" minlength="3" maxlength="64" clearable />
        </el-form-item>
        <el-form-item label="区块Id（对接A2）" prop="areaId">
          <el-input v-model="temp.areaId" placeholder="请输入" minlength="3" maxlength="64" clearable />
        </el-form-item>
        <el-form-item label="区块父级节点（对接A2）" prop="areaParentId">
          <el-input v-model="temp.areaParentId" placeholder="请输入" minlength="3" maxlength="64" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSysArea, updateSysArea, findSysProdOrgAll, addSysAreas } from '@/api/base'
// import axios from 'axios'
import splitPane from 'vue-splitpane'
export default {
  name: '',
  components: {
    splitPane
  },
  directives: {},
  filters: {},
  data() {
    return {
      basicData: {
        columns: [
          { config: { title: '区块', field: 'areaName' }, type: 'tree' },
          { config: { title: '区块代码', field: 'areaCode' }},
          { config: { title: '区块Id', field: 'areaId' }},
          { config: { title: '创建日期', width: '160', field: 'createTime' }, type: 'time' },
          { config: { title: '操作', field: 'opt', width: '180' }, type: 'render',
            render: (h, scope) => {
              return (
                <div>
                  <el-button size='mini' v-permission="'update'" plain type='primary' onClick={() => this.handleUpdate(scope.row)}><i class='el-icon-edit'></i> 编辑</el-button>
                  <el-button type='danger' v-permission="'delete'" plain size='mini' onClick={() => this.$refs.basePage.handleDelete(scope.row)}><i class='el-icon-delete'></i> 删除</el-button>
                </div>
              )
            }
          }
        ],
        searchOtherData: {
          areaOrgId: null
        },
        searchForm: [
          { type: 'Input', label: '区块名', prop: 'areaName', width: '180px' }
        ],
        searchHandle: [
          { label: '新增', type: 'success', icon: 'el-icon-plus', permission: 'add', handle: () => { this.handleCreate() } }
          // { label: '批量新增', type: 'success', icon: 'el-icon-plus', permission: 'add', handle: () => { this.handleDebantchCreate() } }
        ]

      },
      showDel: false,
      delInfo: {},
      typ: [],
      detail: {},
      roleIdOptions: [],
      orgIdOptions: [],
      orgName: '',
      temp: {
        id: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        // areaOrgId: [{ required: true, message: '请输入生产单位', trigger: ['blur', 'change'] }],
        areaName: [{ required: true, message: '请输入区块', trigger: ['blur', 'change'] }]
      },
      downloadLoading: false,
      orgOption: [],
      areaArr: [],
      defaultProps: {
        children: 'children',
        label: 'prodOrgName'
      }
    }
  },
  computed: {},
  created() {
    this.getType()
    // axios('/xml/dzdygx.xml').then((res) => {
    //   const xml = this.$x2js.xml2js(res.data)
    //   const gxData = xml.DataTable.diffgram.DocumentElement.data
    //   const info = gxData.filter((item) => {
    //     return item.ORG_ID === 'DGaYNiYArL' && item.GEO_UNIT_GRADE === '241'
    //   })
    //   info.sort((a, b) => {
    //     return (a.GEO_UNIT_GRADE + '') > (b.GEO_UNIT_GRADE + '') ? 1 : -1
    //   })
    //   console.log(info)
    //   axios('/xml/dzdy.xml').then((res) => {
    //     const dz = this.$x2js.xml2js(res.data)
    //     const dzData = dz.DataTable.diffgram.DocumentElement.data
    //     const arr = []
    //     info.forEach((item) => {
    //       dzData.forEach((i) => {
    //         if (item.GEO_UNIT_ID === i.GEO_UNIT_ID) {
    //           const obj = Object.assign({}, i)
    //           obj.PARENT_GEO_UNIT_ID = item.PARENT_GEO_UNIT_ID
    //           arr.push(obj)
    //         }
    //       })
    //     })
    //     console.log(arr)
    //     this.areaArr = arr.map((item) => {
    //       return {
    //         areaOrgId: '744094221848866817',
    //         areaOrgName: '勘探事业部',
    //         areaCode: item.GEO_UNIT_CODE,
    //         areaId: item.GEO_UNIT_ID,
    //         areaName: item.GEO_UNIT_NAME,
    //         areaDesc: item.REMARKS,
    //         areaParentId: item.PARENT_GEO_UNIT_ID
    //       }
    //     })
    //     console.log(this.areaArr)
    //   })
    // })
  },
  mounted() {
  },
  methods: {
    handleNodeClick(val) {
      this.basicData.searchOtherData.areaOrgId = val.id
      this.$refs.basePage.getList()
    },
    getType() {
      findSysProdOrgAll().then((response) => {
        this.orgOption = response.data
        this.$nextTick(() => {
          if (response.data && response.data.length > 0) {
            this.$refs.tree.setCurrentKey(response.data[0].id)
            this.basicData.searchOtherData.areaOrgId = response.data[0].id
            this.$refs.basePage.getList()
            this.temp.id = response.data[0].id
          }
        })
      })
    },
    // 业务逻辑
    resetTemp() {
      this.temp = {
        id: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.orgName = ''
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addSysArea(this.temp).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // const tempData = Object.assign({}, this.temp)
          const tempData = {}
          tempData.id = this.temp.id
          tempData.areaName = this.temp.areaName
          tempData.areaOrgId = this.temp.areaOrgId
          tempData.areaCode = this.temp.areaCode
          tempData.areaId = this.temp.areaId
          updateSysArea(tempData).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    // 刷新
    handleReset() {
      this.$refs.basePage.getList()
    },
    handleDebantchCreate() {
      this.$confirm('此操作将批量新增, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        addSysAreas(this.areaArr).then(response => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '新增成功',
            type: 'success',
            duration: 2000
          })
          this.handleReset()
        })
      })
    }
  }
}
</script>

<style scoped>
.warning{
  text-align: center;
  font-size: 20px;
}
.el-icon-info{
  font-size: 30px;
  color: orange;
}
</style>
